package org.lionsoul.websnail.task;

import org.apache.commons.lang3.StringUtils;
import org.lionsoul.websnail.Spider;
import org.lionsoul.websnail.analyzer.Analyzer;
import org.lionsoul.websnail.downloader.Downloader;
import org.lionsoul.websnail.downloader.Page;
import org.lionsoul.websnail.util.UrlProcessor;

/**
 * Spider page task handler
 * basic steps:
 * 1. download html page
 * 2. analysis html page (invoke the Analyzer)
 *
 * @author chenxin<chenxin619315 @ gmail.com>
 */
public class DefaultTask implements Task
{
    private final Spider spider;
    private String url;

    public DefaultTask(Spider spider, String url)
    {
        this.spider = spider;
        this.url = url;
    }

    @Override
    public void run()
    {
        /*
         * check and invoke the url processor
         * 	to get a final url to send a http request
         */
        String requestUrl = url;
        UrlProcessor urlProcessor = spider.getOptions().getUrlProcessor();
        if (null != urlProcessor) {
            requestUrl = urlProcessor.process(url);
        }

        /*
         * the request_url may be null after process by urlProcessor
         * here, just pass the task
         */
        if (requestUrl == null) {
            return;
        }

        // download web page
        Downloader downloader = spider.getOptions().getDownloader();
        String html = downloader.process(spider, url);
        if (!StringUtils.isBlank(html)) {
            Page page = Page.create().setOriginUrl(url).setUrl(requestUrl).setHtml(html);

            //invoke the page analyzer to process the page
            Analyzer analyzer = spider.getOptions().getAnalyzerFactory().create();
            //task listener callback
            if (spider.getOptions().getTaskListener() != null) {
                spider.getOptions().getTaskListener().onSuccess(spider, this);
            }
            if (analyzer != null) {
                analyzer.process(spider, page);
            }
        } else {
            //task listener callback
            if (spider.getOptions().getTaskListener() != null) {
                spider.getOptions().getTaskListener().onFailed(spider, this);
            }
        }
    }

    @Override
    public DefaultTask setUrl(String url)
    {
        this.url = url;
        return this;
    }

    @Override
    public String getUrl()
    {
        return url;
    }

}
